package xyz.strasae.androidlearn.regiongrow.task;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import xyz.strasae.androidlearn.regiongrow.utils.BitmapUtil;
import xyz.strasae.androidlearn.regiongrow.utils.DateUtil;
import xyz.strasae.androidlearn.regiongrow.utils.HttpRequestUtil;
import xyz.strasae.androidlearn.regiongrow.utils.tool.HttpReqData;
import xyz.strasae.androidlearn.regiongrow.utils.tool.HttpRespData;

public class GetImageCodeTask extends AsyncTask<Void, Void, String> {
    private final static String TAG = "GetImageCodeTask";
    private Context mContext;
    private String mImageCodeUrl;

    public GetImageCodeTask(Context context, String mImageCodeUrl) {
        super();
        mContext = context;
        this.mImageCodeUrl = mImageCodeUrl;
    }

    @Override
    protected String doInBackground(Void... params) {
        String url = mImageCodeUrl;
        Log.d(TAG, "image url="+url);
        HttpReqData req_data = new HttpReqData(url);
        HttpRespData resp_data = HttpRequestUtil.getImage(req_data);
        String path = BitmapUtil.getCachePath(mContext) + DateUtil.getNowDateTime(null) + ".jpg";
        BitmapUtil.saveBitmap(path, resp_data.bitmap, "jpg", 80);
        Log.d(TAG, "image path="+path);
        return path;
    }

    @Override
    protected void onPostExecute(String path) {
        mListener.onGetCode(path);
    }

    private OnImageCodeListener mListener;
    public void setOnImageCodeListener(OnImageCodeListener listener) {
        mListener = listener;
    }

    public static interface OnImageCodeListener {
        public abstract void onGetCode(String path);
    }
}

